<template>
  <div class="hospital-finder-container">
    <!-- 搜索和筛选区域 -->
    <div class="search-section">
      <el-input
          v-model="searchQuery"
          placeholder="输入医院名称或地址"
          clearable
          class="search-input"
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>

      <el-select
          v-model="selectedLevel"
          placeholder="医院等级"
          clearable
          class="filter-select"
      >
        <el-option
            v-for="level in hospitalLevels"
            :key="level.value"
            :label="level.label"
            :value="level.value"
        />
      </el-select>

      <el-select
          v-model="selectedDepartment"
          placeholder="重点科室"
          clearable
          class="filter-select"
      >
        <el-option
            v-for="dept in departments"
            :key="dept.value"
            :label="dept.label"
            :value="dept.value"
        />
      </el-select>
    </div>

    <!-- 地图和列表视图切换 -->
    <div class="view-toggle">
      <el-radio-group v-model="viewMode" size="large">
        <el-radio-button label="list">列表视图</el-radio-button>
      </el-radio-group>
    </div>

    <!-- 列表视图 -->
    <div v-if="viewMode === 'list'" class="hospital-list">
      <el-card
          v-for="hospital in filteredHospitals"
          :key="hospital.id"
          class="hospital-card"
          shadow="hover"
      >
        <div class="hospital-info">
          <div class="hospital-header">
            <h3>{{ hospital.name }}</h3>
            <el-tag :type="getLevelTag(hospital.level)">
              {{ hospital.level }}
            </el-tag>
          </div>
          <div class="hospital-meta">
            <span><el-icon><Location /></el-icon> {{ hospital.address }}</span>
            <span><el-icon><Phone /></el-icon> {{ hospital.phone }}</span>
          </div>
          <div class="hospital-departments">
            <el-tag
                v-for="dept in hospital.featuredDepartments"
                :key="dept"
                type="info"
                size="small"
            >
              {{ dept }}
            </el-tag>
          </div>
          <div class="hospital-actions">
            <el-button type="primary" size="small" @click="navigateToHospital(hospital)">
              导航
            </el-button>
            <el-button size="small" @click="showDetail(hospital)">
              详情
            </el-button>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 医院详情对话框 -->
    <el-dialog
        v-model="detailVisible"
        :title="currentHospital.name"
        width="50%"
    >
      <div class="hospital-detail">
        <div class="detail-row">
          <span class="label">医院等级:</span>
          <el-tag :type="getLevelTag(currentHospital.level)">
            {{ currentHospital.level }}
          </el-tag>
        </div>
        <div class="detail-row">
          <span class="label">医院地址:</span>
          <span>{{ currentHospital.address }}</span>
        </div>
        <div class="detail-row">
          <span class="label">联系电话:</span>
          <span>{{ currentHospital.phone }}</span>
        </div>
        <div class="detail-row">
          <span class="label">急诊服务:</span>
          <span>{{ currentHospital.emergency ? '24小时开放' : '无' }}</span>
        </div>
        <div class="detail-row">
          <span class="label">特色科室:</span>
          <div class="departments">
            <el-tag
                v-for="dept in currentHospital.featuredDepartments"
                :key="dept"
                type="info"
                size="small"
            >
              {{ dept }}
            </el-tag>
          </div>
        </div>
        <div class="detail-row">
          <span class="label">医院简介:</span>
          <p class="description">{{ currentHospital.description }}</p>
        </div>
      </div>
      <template #footer>
        <el-button @click="detailVisible = false">关闭</el-button>
        <el-button type="primary" @click="navigateToHospital(currentHospital)">
          导航前往
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { Search, Location, Phone } from '@element-plus/icons-vue'
import axios from 'axios'

// 数据状态
const searchQuery = ref('')
const selectedLevel = ref('')
const selectedDepartment = ref('')
const viewMode = ref('list')
const detailVisible = ref(false)
const currentHospital = ref({})
const hospitals = ref([])

// 下拉框选项数据（初始为空，将从后端获取）
const hospitalLevels = ref([])
const departments = ref([])
// 获取医院数据
const fetchHospitals = async () => {
  try {
    const response = await axios.get('http://localhost:6063/api/hospitals/all')
    hospitals.value = response.data.map(hospital => ({
      ...hospital,
      // 转换后端数据格式为前端需要的格式
      emergency: hospital.emergency === 1,
      featuredDepartments: JSON.parse(hospital.departments || '[]'),
      location: [hospital.longitude, hospital.latitude] // 注意顺序
    }))
    console.log('从后端获取的医院数据:', hospitals.value) // 打印后端返回的数据
  } catch (error) {
    console.error('获取医院数据失败:', error)
    hospitals.value = [] // 失败时设为空数组
  }
}

// 新增：获取医院等级和科室选项数据
const fetchFilterOptions = async () => {
  try {
    // 假设后端有这两个API端点
    const [levelsRes, deptsRes] = await Promise.all([
      axios.get('http://localhost:6063/api/hospitals/levels'),
      axios.get('http://localhost:6063/api/hospitals/departments')
    ])

    hospitalLevels.value = levelsRes.data.map(level => ({
      value: level,
      label: level
    }))

    departments.value = deptsRes.data.map(dept => ({
      value: dept,
      label: dept
    }))
  } catch (error) {
    console.error('获取筛选选项失败:', error)
    // 可以设置默认值或显示错误信息
  }
}


// 计算属性
const filteredHospitals = computed(() => {
  return hospitals.value.filter(hospital => {
    const matchesSearch = hospital.name.includes(searchQuery.value) ||
        hospital.address.includes(searchQuery.value)
    const matchesLevel = !selectedLevel.value ||
        hospital.level === selectedLevel.value
    const matchesDept = !selectedDepartment.value ||
        hospital.featuredDepartments.some(dept =>
            dept === selectedDepartment.value)
    return matchesSearch && matchesLevel && matchesDept
  })
})

// 方法
function getLevelTag(level) {
  const levelMap = {
    '三级甲等': 'danger',
    '三级乙等': 'warning',
    '二级甲等': 'success',
    '二级乙等': 'info',
    '一级': ''
  }
  return levelMap[level] || ''
}

function showDetail(hospital) {
  currentHospital.value = hospital
  detailVisible.value = true
}

function navigateToHospital(hospital) {
  // 实际项目中这里会调用地图API进行导航
  console.log('导航至:', hospital.name, hospital.location)
  window.open(`https://map.baidu.com/?latlng=${hospital.location[1]},${hospital.location[0]}&title=${hospital.name}`)
}

// 组件挂载时获取数据
onMounted(() => {
  fetchHospitals()
  fetchFilterOptions()
})
</script>

<style scoped>
.hospital-finder-container {
  padding: 20px;
}
.search-section {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
}
.search-input {
  flex: 1;
}
.filter-select {
  width: 150px;
}
.view-toggle {
  margin-bottom: 20px;
  text-align: center;
}
.hospital-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: 20px;
}
.hospital-card {
  cursor: pointer;
  transition: transform 0.2s;
}
.hospital-card:hover {
  transform: translateY(-3px);
}
.hospital-info {
  height: 100%;
  display: flex;
  flex-direction: column;
}
.hospital-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}
.hospital-meta {
  display: flex;
  flex-direction: column;
  gap: 5px;
  color: #666;
  margin-bottom: 10px;
  font-size: 0.9em;
}
.hospital-departments {
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
  margin-bottom: 15px;
}
.hospital-actions {
  margin-top: auto;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
.map-container {
  height: 500px;
  margin-top: 20px;
}
.map {
  width: 100%;
  height: 100%;
  border-radius: 4px;
}
.hospital-detail .detail-row {
  margin-bottom: 15px;
  display: flex;
  align-items: center;
}
.hospital-detail .label {
  width: 80px;
  font-weight: bold;
  margin-right: 10px;
}
.hospital-detail .departments {
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
}
.hospital-detail .description {
  margin-top: 5px;
  color: #666;
  line-height: 1.6;
}
</style>
